{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualization of Segmentation and Registration Results <a href=\"https://mybinder.org/v2/gh/InsightSoftwareConsortium/SimpleITK-Notebooks/master?filepath=Python%2F05_Results_Visualization.ipynb\"><img style=\"float: right;\" src=\"https://mybinder.org/badge_logo.svg\"></a>\n",
    "\n",
    "In this notebook we illustrate various ways one can display the results of segmentation and registration algorithms so that they can be easily incorporated into a manuscript or presentation. For interactive data exploration we recommend using dedicated programs (e.g. 3D slicer). \n",
    "\n",
    "Two key points to remember when working with bio-medical images:\n",
    "\n",
    "1. Most often images have a high dynamic range. Thus, to write them to file in a format appropriate for use in a manuscript or presentation we will need to map the intensities to a low dynamic range (e.g. [0,255]). In SimpleITK this is readily done with the [IntensityWindowingImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1IntensityWindowingImageFilter.html).\n",
    "2. Images may have non-isotropic spacing between pixels. The file formats appropriate for use in manuscripts and presentations (e.g. png, jpg) assume isotropic pixel spacing. This requires that we resample the image before writing to disk. The function `make_isotropic` in the code cell bellow resolves this issue. \n",
    "\n",
    "The following filters and their procedural counterparts are useful for various image creation tasks, as illustrated in this notebook:\n",
    " * [CastImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1CastImageFilter.html)\n",
    " * [ResampleImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ResampleImageFilter.html), one of the more important filters in your toolbox, see [this notebook](21_Transforms_and_Resampling.ipynb) for additional usage details.\n",
    " * [TileImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1TileImageFilter.html)\n",
    " * [CheckerBoardImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1CheckerBoardImageFilter.html)\n",
    " * [ComposeImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ComposeImageFilter.html)\n",
    " * [LabelToRGBImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelToRGBImageFilter.html)\n",
    " * [ScalarToRGBColormapImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ScalarToRGBColormapImageFilter.html)\n",
    " * [LabelOverlayImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelOverlayImageFilter.html)\n",
    " * [LabelContourImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelContourImageFilter.html)\n",
    " * [LabelMapContourOverlayImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1LabelMapContourOverlayImageFilter.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib widget\n",
    "\n",
    "import numpy as np\n",
    "import itertools\n",
    "import SimpleITK as sitk\n",
    "\n",
    "# Utility method that either downloads data from the Girder repository or\n",
    "# if already downloaded returns the file name for reading from disk (cached data).\n",
    "%run update_path_to_download_script\n",
    "from downloaddata import fetch_data as fdata\n",
    "\n",
    "from ipywidgets import interact, fixed\n",
    "import matplotlib.pyplot as plt\n",
    "import gui\n",
    "\n",
    "# Always write output to a separate directory, we don't want to pollute the source directory.\n",
    "import os\n",
    "\n",
    "OUTPUT_DIR = \"Output\"\n",
    "\n",
    "\n",
    "def make_isotropic(\n",
    "    image,\n",
    "    interpolator=sitk.sitkLinear,\n",
    "    spacing=None,\n",
    "    default_value=0,\n",
    "    standardize_axes=False,\n",
    "):\n",
    "    \"\"\"\n",
    "    Many file formats (e.g. jpg, png,...) expect the pixels to be isotropic, same\n",
    "    spacing for all axes. Saving non-isotropic data in these formats will result in\n",
    "    distorted images. This function makes an image isotropic via resampling, if needed.\n",
    "    Args:\n",
    "        image (SimpleITK.Image): Input image.\n",
    "        interpolator: By default the function uses a linear interpolator. For\n",
    "                      label images one should use the sitkNearestNeighbor interpolator\n",
    "                      so as not to introduce non-existant labels.\n",
    "        spacing (float): Desired spacing. If none given then use the smallest spacing from\n",
    "                         the original image.\n",
    "        default_value (image.GetPixelID): Desired pixel value for resampled points that fall\n",
    "                                          outside the original image (e.g. HU value for air, -1000,\n",
    "                                          when image is CT).\n",
    "        standardize_axes (bool): If the original image axes were not the standard ones, i.e. non\n",
    "                                 identity cosine matrix, we may want to resample it to have standard\n",
    "                                 axes. To do that, set this paramter to True.\n",
    "    Returns:\n",
    "        SimpleITK.Image with isotropic spacing which occupies the same region in space as\n",
    "        the input image.\n",
    "    \"\"\"\n",
    "    original_spacing = image.GetSpacing()\n",
    "    # Image is already isotropic, just return a copy.\n",
    "    if all(spc == original_spacing[0] for spc in original_spacing):\n",
    "        return sitk.Image(image)\n",
    "    # Make image isotropic via resampling.\n",
    "    original_size = image.GetSize()\n",
    "    if spacing is None:\n",
    "        spacing = min(original_spacing)\n",
    "    new_spacing = [spacing] * image.GetDimension()\n",
    "    new_size = [\n",
    "        int(round(osz * ospc / spacing))\n",
    "        for osz, ospc in zip(original_size, original_spacing)\n",
    "    ]\n",
    "    new_direction = image.GetDirection()\n",
    "    new_origin = image.GetOrigin()\n",
    "    # Only need to standardize axes if user requested and the original\n",
    "    # axes were not standard.\n",
    "    if standardize_axes and not np.array_equal(\n",
    "        np.array(new_direction), np.identity(image.GetDimension()).ravel()\n",
    "    ):\n",
    "        new_direction = np.identity(image.GetDimension()).ravel()\n",
    "        # Compute bounding box for the original, non standard axes image.\n",
    "        boundary_points = []\n",
    "        for boundary_index in list(\n",
    "            itertools.product(*zip([0] * image.GetDimension(), image.GetSize()))\n",
    "        ):\n",
    "            boundary_points.append(image.TransformIndexToPhysicalPoint(boundary_index))\n",
    "        max_coords = np.max(boundary_points, axis=0)\n",
    "        min_coords = np.min(boundary_points, axis=0)\n",
    "        new_origin = min_coords\n",
    "        new_size = (((max_coords - min_coords) / spacing).round().astype(int)).tolist()\n",
    "    return sitk.Resample(\n",
    "        image,\n",
    "        new_size,\n",
    "        sitk.Transform(),\n",
    "        interpolator,\n",
    "        new_origin,\n",
    "        new_spacing,\n",
    "        new_direction,\n",
    "        default_value,\n",
    "        image.GetPixelID(),\n",
    "    )\n",
    "\n",
    "\n",
    "def write_video_data(image, output_name, reslice_axis=2, fps=None):\n",
    "    \"\"\"\n",
    "    Create a video clip scrolling through a 3D image along a specific axis and\n",
    "    write the result to disk. The result can be either the individual frames\n",
    "    or a video clip. The later depends on OpenCV which is not installed by\n",
    "    default. The former needs to be assembled into a video using an external tool\n",
    "    (e.g. ffmpeg).\n",
    "    Args:\n",
    "        image (SimpleITK.Image): 3D input image.\n",
    "                                 NOTE: Pixel spacings in the non-scrolling axes\n",
    "                                       are expected to be the same (isotropic in\n",
    "                                       that plane). Use the make_isotropic function\n",
    "                                       if they aren't.\n",
    "                                       Pixel type is either sitkUInt8 or sitkVectorUInt8\n",
    "                                       with three components which are assumed to be RGB.\n",
    "        output_name (str): A file name prefix. If the frames-per-second parameter is None then this is\n",
    "                           used as the prefix for saving individual frames in png format. Otherwise,\n",
    "                           this is used as the prefix for saving the video in mp4 format.\n",
    "        reslice_axis (int): Number in [0,1,2]. The axis along which we scroll.\n",
    "        fps (int): Frames per second.\n",
    "    \"\"\"\n",
    "    # Frames are always along the third axis, so set the axis of interest to be the\n",
    "    # third axis via PermuteAxes\n",
    "    permute_axes = [0, 1, 2]\n",
    "    permute_axes[2] = reslice_axis\n",
    "    permute_axes[reslice_axis] = 2\n",
    "    image = sitk.PermuteAxes(image, permute_axes)\n",
    "\n",
    "    if fps is None:  # write slices as individual frames\n",
    "        sitk.WriteImage(\n",
    "            image, [f\"{output_name}{i:03d}.png\" for i in range(image.GetDepth())]\n",
    "        )\n",
    "    else:  # use OpenCV to write slices as mp4 video\n",
    "        video_writer = cv2.VideoWriter(\n",
    "            filename=output_name + \".mp4\",\n",
    "            fourcc=cv2.VideoWriter_fourcc(\"m\", \"p\", \"4\", \"v\"),\n",
    "            fps=fps,\n",
    "            frameSize=image.GetSize()[0:2],\n",
    "            isColor=image.GetNumberOfComponentsPerPixel() == 3,\n",
    "        )\n",
    "        for i in range(image.GetDepth()):\n",
    "            video_writer.write(sitk.GetArrayViewFromImage(image[:, :, i]))\n",
    "        video_writer.release()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combining two images\n",
    "\n",
    "There are a variety of ways we can overlay two (partially) overlapping images onto each other. The common approaches include:\n",
    "1. Use of blending, alpha or Laplacian pyramid based.\n",
    "2. Use of a checkerboard pattern with the pixel values in adjacent squares/boxes taken from each of the images.\n",
    "3. When the pixel values are scalars (gray scale images), combine the two images in different channels, resulting in a color image.\n",
    "\n",
    "We will start by loading two images whose content luckily overlaps in physical space. Before we can combine the two, we need to resample one of them so that they both occupy the same spatial region. In addition we should also rescale the intensities so that they occupy the same range. In our case we will map them to [0,255], based on the desired windowing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img1 = sitk.ReadImage(fdata(\"training_001_mr_T1.mha\"))\n",
    "img2_original = sitk.ReadImage(fdata(\"training_001_ct.mha\"))\n",
    "img2 = sitk.Resample(img2_original, img1)\n",
    "\n",
    "# Obtain foreground masks for the two images using Otsu thresholding, we use these later on.\n",
    "msk1 = sitk.OtsuThreshold(img1, 0, 1)\n",
    "msk2 = sitk.OtsuThreshold(img2, 0, 1)\n",
    "\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[img1, img2], title_list=[\"image1\", \"image2\"], figure_size=(9, 3)\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Having identified the desired intensity range for each of the\n",
    "# images using the GUI above, we use these values to perform intensity windowing and map the intensity values\n",
    "# to [0,255] and cast to 8-bit unsigned int\n",
    "img1_255 = sitk.Cast(\n",
    "    sitk.IntensityWindowing(\n",
    "        img1, windowMinimum=2, windowMaximum=657, outputMinimum=0.0, outputMaximum=255.0\n",
    "    ),\n",
    "    sitk.sitkUInt8,\n",
    ")\n",
    "img2_255 = sitk.Cast(\n",
    "    sitk.IntensityWindowing(\n",
    "        img2,\n",
    "        windowMinimum=-1018,\n",
    "        windowMaximum=1126,\n",
    "        outputMinimum=0.0,\n",
    "        outputMaximum=255.0,\n",
    "    ),\n",
    "    sitk.sitkUInt8,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Blending - alpha blending and Laplacian pyramids\n",
    "\n",
    "**Alpha blending** combines the pixels from the two images as follows:\n",
    "$$\n",
    "I_{output} = \\alpha I_1 + (1-\\alpha)I_2,\\;\\;\\; \\alpha \\in[0.0,1.0]\n",
    "$$\n",
    "\n",
    "The $\\alpha$ value can be per the whole image or on a per pixel basis.\n",
    "\n",
    "When our images consist of a foreground and background we can use alpha blending in a manner that takes this into account. Instead of blending all of the pixels using the formula above, we use this formula only in the regions where the foregrounds overlap. In regions where the foreground from one image overlaps with the background of the other we simply copy the foreground. This improves visibility as we are not blending a region that contains information with an empty region.\n",
    "\n",
    "The code below allows us to experiment with various alpha blending strategies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mask_image_multiply(mask, image):\n",
    "    components_per_pixel = image.GetNumberOfComponentsPerPixel()\n",
    "    if components_per_pixel == 1:\n",
    "        return mask * image\n",
    "    else:\n",
    "        return sitk.Compose(\n",
    "            [\n",
    "                mask * sitk.VectorIndexSelectionCast(image, channel)\n",
    "                for channel in range(components_per_pixel)\n",
    "            ]\n",
    "        )\n",
    "\n",
    "\n",
    "def alpha_blend(image1, image2, alpha=0.5, mask1=None, mask2=None):\n",
    "    \"\"\"\n",
    "    Alaph blend two images, pixels can be scalars or vectors.\n",
    "    The alpha blending factor can be either a scalar or an image whose\n",
    "    pixel type is sitkFloat32 and values are in [0,1].\n",
    "    The region that is alpha blended is controled by the given masks.\n",
    "    \"\"\"\n",
    "\n",
    "    if not mask1:\n",
    "        mask1 = sitk.Image(image1.GetSize(), sitk.sitkFloat32) + 1.0\n",
    "        mask1.CopyInformation(image1)\n",
    "    else:\n",
    "        mask1 = sitk.Cast(mask1, sitk.sitkFloat32)\n",
    "    if not mask2:\n",
    "        mask2 = sitk.Image(image2.GetSize(), sitk.sitkFloat32) + 1\n",
    "        mask2.CopyInformation(image2)\n",
    "    else:\n",
    "        mask2 = sitk.Cast(mask2, sitk.sitkFloat32)\n",
    "    # if we received a scalar, convert it to an image\n",
    "    if type(alpha) != sitk.SimpleITK.Image:\n",
    "        alpha = sitk.Image(image1.GetSize(), sitk.sitkFloat32) + alpha\n",
    "        alpha.CopyInformation(image1)\n",
    "    components_per_pixel = image1.GetNumberOfComponentsPerPixel()\n",
    "    if components_per_pixel > 1:\n",
    "        img1 = sitk.Cast(image1, sitk.sitkVectorFloat32)\n",
    "        img2 = sitk.Cast(image2, sitk.sitkVectorFloat32)\n",
    "    else:\n",
    "        img1 = sitk.Cast(image1, sitk.sitkFloat32)\n",
    "        img2 = sitk.Cast(image2, sitk.sitkFloat32)\n",
    "\n",
    "    intersection_mask = mask1 * mask2\n",
    "\n",
    "    intersection_image = mask_image_multiply(\n",
    "        alpha * intersection_mask, img1\n",
    "    ) + mask_image_multiply((1 - alpha) * intersection_mask, img2)\n",
    "    return (\n",
    "        intersection_image\n",
    "        + mask_image_multiply(mask2 - intersection_mask, img2)\n",
    "        + mask_image_multiply(mask1 - intersection_mask, img1)\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now create 3D images using all four combinations of alpha-blending and masks. As we are working with a 3D image and we want to save it as a figure for use in a manuscript, we will create a 2D montage image using the axial slices from the volumes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Combine the two volumes\n",
    "images_list = [\n",
    "    (alpha_blend(img1_255, img2_255), \"alpha_blend_standard\"),\n",
    "    (alpha_blend(img1_255, img2_255, mask1=msk1), \"alpha_blend_mask1\"),\n",
    "    (alpha_blend(img1_255, img2_255, mask2=msk2), \"alpha_blend_mask2\"),\n",
    "    (\n",
    "        alpha_blend(img1_255, img2_255, mask1=msk1, mask2=msk2),\n",
    "        \"alpha_blend_mask1_mask2\",\n",
    "    ),\n",
    "]\n",
    "\n",
    "# Tile the volumes using the x-y plane (axial slices)\n",
    "all_montages = []\n",
    "for img, img_name in images_list:\n",
    "    num_slices = img.GetDepth()\n",
    "    tile_w = int(np.sqrt(num_slices))\n",
    "    tile_h = int(np.ceil(num_slices / tile_w))\n",
    "    tile_image = sitk.Tile([img[:, :, i] for i in range(num_slices)], (tile_w, tile_h))\n",
    "    sitk.WriteImage(\n",
    "        sitk.Cast(tile_image, sitk.sitkUInt8),\n",
    "        os.path.join(OUTPUT_DIR, img_name + \".png\"),\n",
    "    )\n",
    "    all_montages.append(tile_image)\n",
    "\n",
    "# Display all montages by combining them into a faux volume. Notice that scrolling through this\n",
    "# volume creates the illusion of motion due to the change in intensities (the interested\n",
    "# reader is referred to \"Visual dissociations of movement, position, and stereo depth: Some phenomenal\n",
    "# phenomena\", R. L. Gregory, P. F. Heard).\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[sitk.JoinSeries(all_montages)],\n",
    "    title_list=[\"Montages With Different Alpha Blending Strategies\"],\n",
    "    figure_size=(8, 8),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the next cell, instead of as a montage, we save each 3D image as a video or video frames, scrolling along a user specified axis. This is useful for presentations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Select the axis along which we scroll. For a correct video rendering the spacing on the other\n",
    "# two axes is expected to be equal. If it isn't we can always call the make_isotropic function\n",
    "# defined above.\n",
    "scroll_axis = 2\n",
    "\n",
    "# if OpenCV is installed (by default it isn't) save as mp4 videos\n",
    "try:\n",
    "    import cv2\n",
    "\n",
    "    for img, img_name in images_list:\n",
    "        write_video_data(\n",
    "            sitk.Cast(img, sitk.sitkUInt8),\n",
    "            os.path.join(OUTPUT_DIR, img_name),\n",
    "            reslice_axis=scroll_axis,\n",
    "            fps=15,\n",
    "        )\n",
    "except ImportError:\n",
    "    for img, img_name in images_list:\n",
    "        write_video_data(\n",
    "            sitk.Cast(img, sitk.sitkUInt8),\n",
    "            os.path.join(OUTPUT_DIR, img_name + \"_frame\"),\n",
    "            reslice_axis=scroll_axis,\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Laplacian pyramid** based blending results in smooth transitions between the constituent images. This classic approach was described in P. J. Burt, E. H. Adelson, \"A Multiresolution Spline With Application to Image Mosaics\", ACM Transactions on Graphics, 2(4):217-236, 1983. \n",
    "\n",
    "Using this form of blending will most often yield more visually pleasing results than alpha blending. It should be noted though that in the context of medical image analysis, this may not always be what you want. If there is an alignment error we possibly want it to be clearly visible and not smoothed out by the visualization approach."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def multiresolution_blend(\n",
    "    image1, image2, mask2=None, smoothing_variances=1, level_num=4\n",
    "):\n",
    "    \"\"\"\n",
    "    Classic multi-resolution Laplacian pyramid based blending due to Burt and Adelson:\n",
    "    P. J. Burt, E. H. Adelson, \"A Multiresolution Spline With Application to Image\n",
    "    Mosaics\", ACM Transactions on Graphics, 2(4):217-236, 1983.\n",
    "    \"\"\"\n",
    "    components_per_pixel = image1.GetNumberOfComponentsPerPixel()\n",
    "    if components_per_pixel > 1:\n",
    "        image1 = sitk.Cast(image1, sitk.sitkVectorFloat32)\n",
    "        image2 = sitk.Cast(image2, sitk.sitkVectorFloat32)\n",
    "    else:\n",
    "        image1 = sitk.Cast(image1, sitk.sitkFloat32)\n",
    "        image2 = sitk.Cast(image2, sitk.sitkFloat32)\n",
    "\n",
    "    if not mask2:\n",
    "        mask2 = sitk.Image(image2.GetSize(), sitk.sitkFloat32) + 1\n",
    "        mask2.CopyInformation(image2)\n",
    "    else:\n",
    "        mask2 = sitk.Cast(mask2, sitk.sitkFloat32)\n",
    "\n",
    "    # Create Laplacian pyramids for images and Gaussian pyramid for mask\n",
    "    laplacian_pyramid_image1 = create_laplacian_pyramid(\n",
    "        image1, smoothing_variances, level_num\n",
    "    )\n",
    "    laplacian_pyramid_image2 = create_laplacian_pyramid(\n",
    "        image2, smoothing_variances, level_num\n",
    "    )\n",
    "    gaussian_pyramid_mask2 = [mask2]\n",
    "    for l in range(level_num):\n",
    "        gaussian_pyramid_mask2.append(\n",
    "            reduce(gaussian_pyramid_mask2[-1], smoothing_variances)\n",
    "        )\n",
    "    # Combine the Laplacian pyramid data using the mask and collapse the combined Laplacian pyramid\n",
    "    res = (1 - gaussian_pyramid_mask2[-1]) * laplacian_pyramid_image1[\n",
    "        -1\n",
    "    ] + gaussian_pyramid_mask2[-1] * laplacian_pyramid_image2[-1]\n",
    "    for l1, l2, g2 in zip(\n",
    "        laplacian_pyramid_image1[-2::-1],\n",
    "        laplacian_pyramid_image2[-2::-1],\n",
    "        gaussian_pyramid_mask2[-2::-1],\n",
    "    ):\n",
    "        res = sitk.Resample(res, l1) + (1 - g2) * l1 + g2 * l2\n",
    "    return res\n",
    "\n",
    "\n",
    "def create_laplacian_pyramid(image, smoothing_variances, level_num=4):\n",
    "    gaussian_pyramid = [image]\n",
    "    for l in range(level_num):\n",
    "        gaussian_pyramid.append(reduce(gaussian_pyramid[-1], smoothing_variances))\n",
    "\n",
    "    laplacian_pyramid = [\n",
    "        gaussian_pyramid[l]\n",
    "        - sitk.Resample(gaussian_pyramid[l + 1], gaussian_pyramid[l])\n",
    "        for l in range(level_num)\n",
    "    ]\n",
    "    laplacian_pyramid.append(gaussian_pyramid[-1])\n",
    "    return laplacian_pyramid\n",
    "\n",
    "\n",
    "def reduce(image, smoothing_variances):\n",
    "    if np.isscalar(smoothing_variances):\n",
    "        smoothing_variances = [smoothing_variances] * image.GetDimension()\n",
    "    smoothed_image = sitk.DiscreteGaussian(\n",
    "        image,\n",
    "        variance=smoothing_variances,\n",
    "        maximumKernelWidth=32,\n",
    "        maximumError=0.01,\n",
    "        useImageSpacing=True,\n",
    "    )\n",
    "\n",
    "    original_spacing = image.GetSpacing()\n",
    "    original_size = image.GetSize()\n",
    "    new_size = [int(sz / 2 + 0.5) for sz in original_size]\n",
    "    new_spacing = [\n",
    "        ((original_sz - 1) * original_spc) / (new_sz - 1)\n",
    "        for original_sz, original_spc, new_sz in zip(\n",
    "            original_size, original_spacing, new_size\n",
    "        )\n",
    "    ]\n",
    "    return sitk.Resample(\n",
    "        smoothed_image,\n",
    "        new_size,\n",
    "        sitk.Transform(),\n",
    "        sitk.sitkLinear,\n",
    "        image.GetOrigin(),\n",
    "        new_spacing,\n",
    "        image.GetDirection(),\n",
    "        0.0,\n",
    "        image.GetPixelID(),\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now create 3D images using both the alpha-blending and Laplacian pyramids approaches and visually compare the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gui.MultiImageDisplay(\n",
    "    image_list=[\n",
    "        alpha_blend(img1_255, img2_255, mask2=msk2),\n",
    "        multiresolution_blend(img1_255, img2_255, msk2),\n",
    "    ],\n",
    "    title_list=[\"alpha_blend_mask2\", \"multiresolution_blend_mask2\"],\n",
    "    figure_size=(9, 3),\n",
    "    shared_slider=True,\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Checkerboard\n",
    "\n",
    "Combine the original and the intensity windowed images using the checkerboard pattern. This illustrates the need to map both images to the same intensity range. This is particularly visible in the background region, where both images contain air. \n",
    "\n",
    "You can specify the number of checkerboard tiles per dimension as illustrated below. The actual number of checkerboard tiles depends on the number of pixels per dimension and the specified number of tiles. You may get more tiles than specified, for example try specifying [4,4,7] below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gui.MultiImageDisplay(\n",
    "    image_list=[\n",
    "        sitk.CheckerBoard(img1, img2, [4, 4, 4]),\n",
    "        sitk.CheckerBoard(img1_255, img2_255, (10, 10, 4)),\n",
    "    ],\n",
    "    title_list=[\"original intensities\", \"rescaled intensities\"],\n",
    "    figure_size=(9, 3),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Combine scalar images to create color image\n",
    "\n",
    "There are a variety of ways we can combine the scalar images to create a color image. Some of these combinations should be avoided as they are not discernible by a significant portion of the population (i.e. red-green channel encoding). For additional details see:\n",
    "\n",
    "M. Geissbuehler, T. Lasser, \"How to display data by color schemes compatible with red-green color perception deficiencies\", Opt Express., 21(8):9862-74, 2013.  \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "zeros = sitk.Image(img1_255.GetSize(), img1_255.GetPixelID())\n",
    "zeros.CopyInformation(img1_255)\n",
    "\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[\n",
    "        sitk.Cast(sitk.Compose(img1_255, img2_255, zeros), sitk.sitkVectorUInt8),\n",
    "        sitk.Cast(sitk.Compose(img1_255, img2_255, img1_255), sitk.sitkVectorUInt8),\n",
    "        sitk.Cast(\n",
    "            sitk.Compose(img1_255, 0.5 * img1_255 + 0.5 * img2_255, img2_255),\n",
    "            sitk.sitkVectorUInt8,\n",
    "        ),\n",
    "    ],\n",
    "    title_list=[\"avoid red-green\", \"use magenta-green\", \"use orange-blue\"],\n",
    "    figure_size=(9, 3),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Overlay scalar image onto another via color map\n",
    "\n",
    "In some situations we have an underlying image (spatial structures) and we want to overlay a scalar based pseudo-color image on top of it.\n",
    "\n",
    "This is relevant for presenting co-registered PET/CT data, with the PET providing functional information and the CT providing the underlying spatial structures. A similar use case in the context of deep learning is to display activation maps illustrating the regions in an image on which the network is focusing its attention for the particular class.\n",
    "\n",
    "The two main decisions we make are:\n",
    "1. Selection of pseudo-color scheme using the [ScalarToRGBColormapImageFilter](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ScalarToRGBColormapImageFilter.html) which supports a variety of color maps.\n",
    "2. Alpha blending approach (alpha value per whole image or per pixel, and usage of masks as done above).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "color_maps = {\n",
    "    \"Red\": sitk.ScalarToRGBColormapImageFilter.Red,\n",
    "    \"Green\": sitk.ScalarToRGBColormapImageFilter.Green,\n",
    "    \"Blue\": sitk.ScalarToRGBColormapImageFilter.Blue,\n",
    "    \"Grey\": sitk.ScalarToRGBColormapImageFilter.Grey,\n",
    "    \"Hot\": sitk.ScalarToRGBColormapImageFilter.Hot,\n",
    "    \"Cool\": sitk.ScalarToRGBColormapImageFilter.Cool,\n",
    "    \"Spring\": sitk.ScalarToRGBColormapImageFilter.Spring,\n",
    "    \"Summer\": sitk.ScalarToRGBColormapImageFilter.Summer,\n",
    "    \"Autumn\": sitk.ScalarToRGBColormapImageFilter.Autumn,\n",
    "    \"Winter\": sitk.ScalarToRGBColormapImageFilter.Winter,\n",
    "    \"Copper\": sitk.ScalarToRGBColormapImageFilter.Copper,\n",
    "    \"Jet\": sitk.ScalarToRGBColormapImageFilter.Jet,\n",
    "    \"HSV\": sitk.ScalarToRGBColormapImageFilter.HSV,\n",
    "    \"OverUnder\": sitk.ScalarToRGBColormapImageFilter.OverUnder,\n",
    "}\n",
    "\n",
    "\n",
    "def colormap_dropdown_callback(colormap_name, colormaps_dict, scalar_image):\n",
    "    global overlay_color_img\n",
    "    overlay_color_img = sitk.ScalarToRGBColormap(\n",
    "        scalar_image, colormaps_dict[colormap_name]\n",
    "    )\n",
    "    displayed_image = (\n",
    "        overlay_color_img[:, :, overlay_color_img.GetDepth() // 2]\n",
    "        if overlay_color_img.GetDimension() == 3\n",
    "        else overlay_color_img\n",
    "    )\n",
    "    fig = plt.figure()\n",
    "    plt.imshow(sitk.GetArrayViewFromImage(displayed_image))\n",
    "    plt.axis(\"off\")\n",
    "    fig.canvas.draw_idle()\n",
    "\n",
    "\n",
    "# Create a signed distance map which we will overlay onto the original image using\n",
    "# pseudo-coloring. We are only interested in locations that are at a distance of [0,512] from the object\n",
    "distance_map = sitk.SignedMaurerDistanceMap(msk1)\n",
    "# Get binary region of interest mask.\n",
    "roi = sitk.Cast(distance_map > 0.0, sitk.sitkFloat32) * sitk.Cast(\n",
    "    distance_map < 512.0, sitk.sitkFloat32\n",
    ")\n",
    "roi_distance_map = roi * distance_map\n",
    "\n",
    "overlay_color_img = None\n",
    "interact(\n",
    "    colormap_dropdown_callback,\n",
    "    colormap_name=list(color_maps.keys()),\n",
    "    colormaps_dict=fixed(color_maps),\n",
    "    scalar_image=fixed(roi_distance_map),\n",
    ");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# To see the various options, re-run this cell and change the blending_approach (basic, mask, per_pixel_alpha)\n",
    "blending_approach = \"basic\"\n",
    "\n",
    "if blending_approach == \"basic\":\n",
    "    combined_volume = sitk.Cast(\n",
    "        alpha_blend(sitk.Compose(img1_255, img1_255, img1_255), overlay_color_img),\n",
    "        sitk.sitkVectorUInt8,\n",
    "    )\n",
    "elif blending_approach == \"mask\":\n",
    "    combined_volume = sitk.Cast(\n",
    "        alpha_blend(\n",
    "            sitk.Compose(img1_255, img1_255, img1_255), overlay_color_img, mask2=roi\n",
    "        ),\n",
    "        sitk.sitkVectorUInt8,\n",
    "    )\n",
    "elif blending_approach == \"per_pixel_alpha\":\n",
    "    mmFilter = sitk.MinimumMaximumImageFilter()\n",
    "    mmFilter.Execute(roi_distance_map)\n",
    "    alpha = sitk.Cast(\n",
    "        1.0\n",
    "        - (roi_distance_map - mmFilter.GetMinimum())\n",
    "        / (mmFilter.GetMaximum() - mmFilter.GetMinimum()),\n",
    "        sitk.sitkFloat32,\n",
    "    )\n",
    "    combined_volume = sitk.Cast(\n",
    "        alpha_blend(\n",
    "            sitk.Compose(img1_255, img1_255, img1_255), overlay_color_img, alpha=alpha\n",
    "        ),\n",
    "        sitk.sitkVectorUInt8,\n",
    "    )\n",
    "\n",
    "# Given a volume we can either create a montage as above or we can take a representative\n",
    "# slice (axial/sagittal/coronal). As image formats used in manuscripts assume isotropic\n",
    "# pixels we need to ensure this before we write to disk.\n",
    "all_central_slices = [\n",
    "    combined_volume[:, :, int(combined_volume.GetDepth() / 2.0 + 0.5)],\n",
    "    combined_volume[:, int(combined_volume.GetHeight() / 2.0 + 0.5), :],\n",
    "    combined_volume[int(combined_volume.GetWidth() / 2.0 + 0.5), :, :],\n",
    "]\n",
    "\n",
    "# Resample to isotropic pixels and write to file.\n",
    "for i, img in enumerate(all_central_slices):\n",
    "    all_central_slices[i] = make_isotropic(img)\n",
    "    sitk.WriteImage(\n",
    "        all_central_slices[i], os.path.join(OUTPUT_DIR, f\"color_overlay{i}.png\")\n",
    "    )\n",
    "\n",
    "gui.multi_image_display2D(\n",
    "    [sitk.Tile(all_central_slices, (1, 3))], figure_size=(4, 4), horizontal=False\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combining an image and segmentation\n",
    "\n",
    "To display the results of segmentation in context, we need to overlay them onto the original image. There are two common options for doing this:\n",
    "  1. Map the segmentation labels to a color image and alpha blend onto the original image.\n",
    "  2. Overlay the segmentation boundaries onto the original image.\n",
    "\n",
    "We illustrate both approaches below.\n",
    "\n",
    "For this example we use the Point-validated Pixel-based Breathing Thorax Model (POPI) model. The model is provided by the Léon Bérard Cancer Center & CREATIS Laboratory, Lyon, France. The relevant publication is:\n",
    "\n",
    "J. Vandemeulebroucke, D. Sarrut, P. Clarysse, \"The POPI-model, a point-validated pixel-based breathing thorax model\", Proc. XVth International Conference on the Use of Computers in Radiation Therapy (ICCR), Toronto, Canada, 2007."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load utilities that are specific to the POPI data, the label values associated with the segmentation.\n",
    "%run popi_utilities_setup.py\n",
    "\n",
    "img = sitk.ReadImage(fdata(\"POPI/meta/00-P.mhd\"))\n",
    "segmentation = sitk.ReadImage(fdata(\"POPI/masks/00-air-body-lungs.mhd\"))\n",
    "\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[img, segmentation, sitk.LabelToRGB(segmentation)],\n",
    "    title_list=[\"image\", \"raw segmentation labels\", \"segmentation labels in color\"],\n",
    "    figure_size=(9, 3),\n",
    "    shared_slider=True,\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will work with the central coronal slice from this dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Identify the desired intensity range for our image using the GUI above, mapping the high dynamic range\n",
    "# image to a low dynamic range, [0,255], extract the central coronal slice and we flip it for display purposes.\n",
    "coronal_255 = sitk.Cast(\n",
    "    sitk.IntensityWindowing(\n",
    "        img[:, int(img.GetHeight() / 2), :][:, ::-1],\n",
    "        windowMinimum=-1000,\n",
    "        windowMaximum=170,\n",
    "        outputMinimum=0.0,\n",
    "        outputMaximum=255.0,\n",
    "    ),\n",
    "    sitk.sitkUInt8,\n",
    ")\n",
    "coronal_255_isotropic = make_isotropic(coronal_255)\n",
    "\n",
    "coronal_segmentation = segmentation[:, int(segmentation.GetHeight() / 2), :][:, ::-1]\n",
    "# Use nearest neighbor interpolation for a label image.\n",
    "coronal_segmentation_isotropic = make_isotropic(\n",
    "    coronal_segmentation, sitk.sitkNearestNeighbor\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In many cases the values in a label image are not appropriate for direct display. For instance the values in our\n",
    "label image are 0,1,2. You can see the values if you hover your cursor over the raw segmentation label image above (figure's bottom right corner). \n",
    "\n",
    "In theory we could map these intensities to [0,255] and save the image. In practice we may have more than 256 labels and therefor it is preferable to map the labels to colors and save the color image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the default color map when mapping labels to colors and write the image.\n",
    "sitk.WriteImage(\n",
    "    sitk.LabelToRGB(coronal_segmentation_isotropic),\n",
    "    os.path.join(OUTPUT_DIR, \"coronal_segmentation.png\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Overlay segmentation labels onto original image\n",
    "\n",
    "SimpleITK allows you to overlay the segmentation labels onto the original image using a color map and alpha blending. You can specify the value for alpha blending, the color map (there is a default color map), and the background label value which will not be overlaid with a label.\n",
    "\n",
    "The color map in SimpleITK is a set of values in the RGB color space strung together. For example [255, 0, 0, 0, 255, 0] is a two entry color map with red and green. To create a human readable color map, use lists to represent the colors and string them together, as done below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Overlay the segmentation using default color map and an alpha value of 0.5\n",
    "coronal_combined1 = sitk.LabelOverlay(\n",
    "    image=coronal_255_isotropic,\n",
    "    labelImage=coronal_segmentation_isotropic,\n",
    "    opacity=0.5,\n",
    "    backgroundValue=air_label,\n",
    ")\n",
    "\n",
    "# Create an \"interesting\" color map and specify backgroundValue to a non existent label\n",
    "# so that the background label is also overlaid.\n",
    "pink = [255, 105, 180]\n",
    "green = [0, 255, 0]\n",
    "gold = [255, 215, 0]\n",
    "coronal_combined2 = sitk.LabelOverlay(\n",
    "    image=coronal_255_isotropic,\n",
    "    labelImage=coronal_segmentation_isotropic,\n",
    "    opacity=0.5,\n",
    "    backgroundValue=-1.0,\n",
    "    colormap=pink + green + gold,\n",
    ")\n",
    "\n",
    "# Display the two images as a faux volume, JoinSeries, approach.\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[sitk.JoinSeries([coronal_combined1, coronal_combined2])],\n",
    "    title_list=[\"overlaid labels\"],\n",
    "    figure_size=(9, 3),\n",
    "    shared_slider=True,\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Overlay segmentation boundaries onto original image\n",
    "\n",
    "We can readily obtain the segmentation boundaries from the raw segmentation. We then either just save the contours as an image or we can directly overly them onto the image. \n",
    "\n",
    "Some points to note:\n",
    " 1. When working with 3D images and segmentations, our boundaries are surfaces. When these surfaces are intersected  with 2D planes they may define a region and not a contour, which is what we usually expect (e.g. slice 24 in the results displayed by the following code cell).\n",
    " 2. When the labels are next to each other, they share a boundary. As a consequence, drawing the boundaries may result in contours overwriting each other or in contour crossings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "red = [255, 0, 0]\n",
    "green = [0, 255, 0]\n",
    "blue = [0, 0, 255]\n",
    "\n",
    "# red goes to the first label, green to second, blue to third\n",
    "# body_label=0, air_label=1, lung_label=2\n",
    "contour_image = sitk.LabelToRGB(\n",
    "    sitk.LabelContour(segmentation, fullyConnected=True, backgroundValue=255),\n",
    "    colormap=red + green + blue,\n",
    "    backgroundValue=255,\n",
    ")\n",
    "gui.MultiImageDisplay(image_list=[contour_image], figure_size=(9, 3));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following code cell we overlay the contours onto the original image. We use a filter that is intended for usage with a label-map image as opposed to a label image. The former is a more efficient data structure for representing segmentations (run length encoded). We therefor need to cast the label image to a label-map image.\n",
    "We can also set several visualization related parameters such as overlay opacity, contour thickness, priority of overlay (which label overwrites which if they overlap) etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "contour_overlaid_image = sitk.LabelMapContourOverlay(\n",
    "    sitk.Cast(coronal_segmentation_isotropic, sitk.sitkLabelUInt8),\n",
    "    coronal_255_isotropic,\n",
    "    opacity=1,\n",
    "    contourThickness=[4, 4],\n",
    "    dilationRadius=[3, 3],\n",
    "    colormap=red + green + blue,\n",
    ")\n",
    "gui.multi_image_display2D([contour_overlaid_image], figure_size=(6, 3));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparing segmentations\n",
    "\n",
    "In this section we show how to create a binary image illustrating all the locations where two segmentations differ. This is a trivial one liner in SimpleITK.\n",
    "\n",
    "The following cell modifies our original coronal segmentation by dilating the body region in the top half of the image and dilating the lung region in the bottom half of the image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "binary_dilate_filter = sitk.BinaryDilateImageFilter()\n",
    "binary_dilate_filter.SetKernelRadius(2)\n",
    "mid_size = int(coronal_segmentation_isotropic.GetHeight() / 2)\n",
    "\n",
    "# Over-segment the body region on the upper image region.\n",
    "binary_dilate_filter.SetForegroundValue(body_label)\n",
    "top_segmentation = binary_dilate_filter.Execute(\n",
    "    coronal_segmentation_isotropic[:, 0:mid_size]\n",
    ")\n",
    "# Over-segment the lung region on the lower image region.\n",
    "binary_dilate_filter.SetForegroundValue(lung_label)\n",
    "bottom_segmentation = binary_dilate_filter.Execute(\n",
    "    coronal_segmentation_isotropic[:, mid_size:]\n",
    ")\n",
    "\n",
    "modified_segmentation = sitk.Tile(top_segmentation, bottom_segmentation, (1, 2))\n",
    "modified_segmentation.CopyInformation(coronal_segmentation_isotropic)\n",
    "# Faux volume which allows us to visually compare the two segmentations by switching back and\n",
    "# forth between them.\n",
    "gui.MultiImageDisplay(\n",
    "    image_list=[sitk.JoinSeries(coronal_segmentation_isotropic, modified_segmentation)],\n",
    "    figure_size=(6, 3),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see where the two segmentations differ, we directly compare them. If we don't want to waste ink, we can invert the result so that black pixels are the foreground and white the background. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "diff_image = coronal_segmentation_isotropic != modified_segmentation\n",
    "sitk.WriteImage(\n",
    "    diff_image * 255, os.path.join(OUTPUT_DIR, \"segmentation_differences.jpg\")\n",
    ")\n",
    "sitk.WriteImage(\n",
    "    (diff_image != 1) * 255,\n",
    "    os.path.join(OUTPUT_DIR, \"segmentation_differences_inverted.jpg\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When dealing with **multiple binary** segmentations we can overlay the boundaries onto the original image as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def overlay_segmentations(\n",
    "    image,\n",
    "    binary_segmentations,\n",
    "    thickness,\n",
    "    dilation_radius,\n",
    "    colors=[\n",
    "        [230, 159, 0],  # orange\n",
    "        [86, 180, 233],  # sky blue\n",
    "        [0, 158, 115],  # bluish green\n",
    "        [240, 228, 66],  # yellow\n",
    "        [0, 114, 178],  # blue\n",
    "        [213, 94, 0],  # vermilion\n",
    "        [204, 121, 167],  # reddish purple\n",
    "        [153, 153, 153],  # gray\n",
    "    ],\n",
    "):\n",
    "    \"\"\"\n",
    "    Parameters\n",
    "    ----------\n",
    "    image (SimpleITK.Image): Image on which to overlay segmentations. Expected to be a scalar image with a pixel type of sitkUInt8.\n",
    "    binary_segmentations (Iterable[SimpleITK.Image]):\n",
    "    thickness (Tuple): Thickness of contour or surface along each axis (data is 2D or 3D).\n",
    "    dilation_radius (Tuple): Dilation radius along each axis.\n",
    "    colors (Iterable[Tuple(3)]): Color to use for each binary segmentation (except black [0,0,0]).\n",
    "                                 The iterable is expected to contain a set of colors with at least as\n",
    "                                 many entries as the binary segmentations. If not, a\n",
    "                                 ValueError is raised. Default setting is the colorblind friendly\n",
    "                                Okabe-Ito palette minus the first entry which is black\n",
    "                                (M. Okabe, K. Ito, \"Color universal design (CUD): How to make\n",
    "                                figures and presentations that are friendly to colorblind people\", 2008.).\n",
    "    Returns\n",
    "    -------\n",
    "    SimpleITK.Image - Original image with segmentation contours/surfaces overlaid onto it in color.\n",
    "\n",
    "    Raises\n",
    "    ------\n",
    "    ValueError - If the number of entries in the colors iterable is less than the number of binary segmentations.\n",
    "\n",
    "    \"\"\"\n",
    "    if len(binary_segmentations) > len(colors):\n",
    "        raise ValueError(\n",
    "            \"Number of segmentations is larger than number of colors, not allowed\"\n",
    "        )\n",
    "    for c in colors:\n",
    "        if c == [0, 0, 0]:\n",
    "            raise ValueError(\"Colors include black [0,0,0], not allowed\")\n",
    "    empty_image = image * 0\n",
    "    overlay_boundaries = [\n",
    "        sitk.LabelMapContourOverlay(\n",
    "            sitk.Cast(seg, sitk.sitkLabelUInt8),\n",
    "            empty_image,\n",
    "            opacity=1,\n",
    "            contourThickness=thickness,\n",
    "            dilationRadius=dilation_radius,\n",
    "            colormap=color,\n",
    "        )\n",
    "        for seg, color in zip(binary_segmentations, colors)\n",
    "    ]\n",
    "\n",
    "    current_image = sitk.Compose([image] * 3)\n",
    "    for o_image in overlay_boundaries:\n",
    "        current_mask = (\n",
    "            sitk.NaryAdd(\n",
    "                [\n",
    "                    sitk.VectorIndexSelectionCast(o_image, 0),\n",
    "                    sitk.VectorIndexSelectionCast(o_image, 1),\n",
    "                    sitk.VectorIndexSelectionCast(o_image, 2),\n",
    "                ]\n",
    "            )\n",
    "            == 0\n",
    "        )\n",
    "        current_image = mask_image_multiply(current_mask, current_image) + o_image\n",
    "    return current_image\n",
    "\n",
    "\n",
    "binary_segmentations = [\n",
    "    coronal_segmentation_isotropic == lung_label,\n",
    "    modified_segmentation == lung_label,\n",
    "]\n",
    "gui.multi_image_display2D(\n",
    "    [\n",
    "        overlay_segmentations(\n",
    "            coronal_255_isotropic, binary_segmentations, [3, 3], [2, 2]\n",
    "        )\n",
    "    ],\n",
    "    figure_size=(6, 3),\n",
    ");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When visually comparing a segmentation to a reference we would like to be more detailed, identifying the regions where the two agree and the regions where we have over/under segmentation. The function defined in the next cell creates a three label image with labels corresponding to each of these categories. In addition to the image information, we also add entries to the meta-data dictionary which make the result compatible with the Slicer [.seg.nrrd file format](https://apidocs.slicer.org/master/classvtkMRMLSegmentationStorageNode.html#details). Saving the resulting image in a file with the .seg.nrrd extension allows us to use Slicer to overlay the results onto the anatomical image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def visual_comparison_of_segmentation(\n",
    "    reference_segmentation,\n",
    "    input_segmentation,\n",
    "    reference_label_to_use=None,\n",
    "    input_label_to_use=None,\n",
    "    agreement_label=1,\n",
    "    oversegmentation_label=2,\n",
    "    undersegmentation_label=3,\n",
    "):\n",
    "    \"\"\"\n",
    "    Compare segmentation to a reference segmentation. Create an image with three labels denoting\n",
    "    agreement region, oversegmentation region and undersegmentation region.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    reference_segmentation (SimpleITK.Image): Reference segmentation to which we\n",
    "                                              compare the given segmentation,\n",
    "                                              can be multi-labeled. By default, all\n",
    "                                              non zero values are considered as the\n",
    "                                              segmented object.\n",
    "    input_segmentation (SimpleITK.Image): Input segmentation which is compared\n",
    "                                          to the reference segmentation, can be\n",
    "                                          multi-labeled. By default, all\n",
    "                                          non zero values are considered as the\n",
    "                                          segmented object.\n",
    "\n",
    "    reference_label_to_use (int): Label associated with the object of interest in the\n",
    "                                  reference segmentation. If None then all non zero\n",
    "                                  values belong to the object of interest.\n",
    "    input_label_to_use (int): Label associated with the object of interest in the\n",
    "                              input segmentation. If None then all non zero\n",
    "                              values belong to the object of interest.\n",
    "    agreement_label (int): Label denoting segmentation agreement region in output.\n",
    "    oversegmentation_label (int): Label denoting over segmentation region in output.\n",
    "    undersegmentation_label (int): Label denoting under segmentation region in output.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    SimpleITK.Image - Three label image for visual comparisson of binary segmentations.\n",
    "\n",
    "    \"\"\"\n",
    "    if reference_label_to_use is None:\n",
    "        bin_rs = reference_segmentation != 0\n",
    "    else:\n",
    "        bin_rs = reference_segmentation == reference_label_to_use\n",
    "    if input_label_to_use is None:\n",
    "        bin_is = input_segmentation != 0\n",
    "    else:\n",
    "        bin_is = input_segmentation == input_label_to_use\n",
    "    agree_image = bin_rs * bin_is * agreement_label\n",
    "    diff_image = bin_rs != bin_is\n",
    "    oversegmentation_image = diff_image * bin_is * oversegmentation_label\n",
    "    undersegmentation_image = diff_image * bin_rs * undersegmentation_label\n",
    "    diff_image = sitk.Cast(\n",
    "        agree_image + oversegmentation_image + undersegmentation_image, sitk.sitkUInt8\n",
    "    )\n",
    "\n",
    "    # set metadata dictionary entries so that segmentation is\n",
    "    # compatible with Slicer seg.nrrd file type.\n",
    "    # Slicer specific meta-data value definitions are available\n",
    "    # here https://apidocs.slicer.org/master/classvtkMRMLSegmentationStorageNode.html#details\n",
    "    extent = f\"0 {diff_image.GetWidth()-1} 0 {diff_image.GetHeight()-1} 0 {diff_image.GetDepth()-1}\"\n",
    "    seg_tags = \"Segmentation category and type - 3D Slicer General Anatomy list~SCT^85756007^Tissue~SCT^85756007^Tissue~^^~Anatomic codes - DICOM master list~^^~^^|\"\n",
    "    label_metadata_settings = [\n",
    "        (\n",
    "            \"Segment{seg_num}_Name\",\n",
    "            [\"Agreement region\", \"Oversegmentation region\", \"Undersegmentation region\"],\n",
    "        ),\n",
    "        (\n",
    "            \"Segment{seg_num}_LabelValue\",\n",
    "            [\n",
    "                str(agreement_label),\n",
    "                str(oversegmentation_label),\n",
    "                str(undersegmentation_label),\n",
    "            ],\n",
    "        ),\n",
    "        (\"Segment{seg_num}_Color\", [\"1.0 0.0 0.0\", \"0.0 1.0 0.0\", \"0.0 0.0 1.0\"]),\n",
    "        (\"Segment{seg_num}_ID\", [\"1\", \"2\", \"3\"]),\n",
    "        (\"Segment{seg_num}_Layer\", [\"0\", \"0\", \"0\"]),\n",
    "        (\"Segment{seg_num}_Extent\", [extent, extent, extent]),\n",
    "        (\"Segment{seg_num}_ColorAutoGenerated\", [\"0\", \"0\", \"0\"]),\n",
    "        (\"Segment{seg_num}_NameAutoGenerated\", [\"0\", \"0\", \"0\"]),\n",
    "        (\"Segment{seg_num}_Tags\", [seg_tags, seg_tags, seg_tags]),\n",
    "    ]\n",
    "\n",
    "    diff_image.SetMetaData(\"Segmentation_MasterRepresentation\", \"Binary labelmap\")\n",
    "    diff_image.SetMetaData(\"Segmentation_ReferenceImageExtentOffset\", \"0 0 0\")\n",
    "    diff_image.SetMetaData(\n",
    "        \"Segmentation_ContainedRepresentationNames\", \"Binary labelmap|\"\n",
    "    )\n",
    "    for i in range(3):\n",
    "        for tag, values in label_metadata_settings:\n",
    "            diff_image.SetMetaData(tag.format(seg_num=i), values[i])\n",
    "    return diff_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "anatomical_image = sitk.ReadImage(fdata(\"POPI/meta/00-P.mhd\"))\n",
    "reference = sitk.ReadImage(fdata(\"POPI/masks/00-air-body-lungs.mhd\"))\n",
    "segmentation = sitk.ReadImage(fdata(\"POPI/masks/90-air-body-lungs.mhd\"))\n",
    "comparison_result = visual_comparison_of_segmentation(\n",
    "    reference,\n",
    "    segmentation,\n",
    "    reference_label_to_use=lung_label,\n",
    "    input_label_to_use=lung_label,\n",
    ")\n",
    "# The usage of the .seg.nrrd extension allows Slicer to automatically identify the file as a segmentation.\n",
    "sitk.WriteImage(\n",
    "    comparison_result,\n",
    "    os.path.join(OUTPUT_DIR, \"segmentation_visualization.seg.nrrd\"),\n",
    "    useCompression=True,\n",
    "    compressor=\"gzip\",\n",
    ")\n",
    "\n",
    "# Finally, open the anatomical image in Slicer (Data/POPI/meta/00-P.mhd) then open the result (Output/segmentation_visualization.seg.nrrd) and\n",
    "# you can see the regions where there is agreement or over/under segmentation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overlay bounding boxes onto an image\n",
    "\n",
    "When performing object detection in 2D images we would like to visualize the bounding boxes of our reference data and of our results. The following code cells illustrate how to do this using SimpleITK. Note that the code accommodates for several common options of specifying a bounding box, including normalized, [0,1], and absolute values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def overlay_bounding_boxes(\n",
    "    image,\n",
    "    bounding_boxes,\n",
    "    bounding_box_format=\"MINXY_MAXXY\",\n",
    "    normalized=False,\n",
    "    colors=[],\n",
    "    half_line_width=0,\n",
    "):\n",
    "    \"\"\"\n",
    "    Overlay bounding boxes on an image. The function supports several ways of specifying the\n",
    "    bounding box:\n",
    "    \"MINXY_MAXXY\" - [min_x, min_y, max_x, max_y]\n",
    "    \"MINXY_WH\" - [min_x, min_y, width, height]\n",
    "    \"CENT_WH\" - [center_x, center_y, width, height]\n",
    "    \"CENT_HALFWH\" - [center_x, center_y, width/2, height/2]\n",
    "    Bounding boxes are plotted in the order they appear in the iterable/list. To change the overlap between rectangles\n",
    "    change the order in the list. The last entry in the list will be plotted on top of the previous ones.\n",
    "\n",
    "    Caveat: When using larger line widths, bounding boxes that are very close to the image border may cause an exception\n",
    "            and result in partial overlay. A trivial solution is to decrease the value of the half_line_width parameter.\n",
    "\n",
    "    Args:\n",
    "    image (SimpleITK.Image(sitk.sitkUInt8 or sitk.sitkVectorUInt8)): Image, 2D with scalar or RGB pixels on which we\n",
    "                                                                     plot the bounding boxes.\n",
    "    bounding_boxes (iterable(tuple/list with four entries)): Bounding boxes to plot.\n",
    "    bounding_box_format (str): One of [\"MINXY_MAXXY\", \"MINXY_WH\", \"CENT_WH\", \"CENT_HALFWH\"] specifying the meaning of\n",
    "                               the four entries representing the bounding box.\n",
    "    normalized (boolean): Indicating whether the bounding box numbers were normalized to be in [0,1].\n",
    "    colors (iterable(tuple/list with three entries)): Specify the color for each rectangle using RGB values in [0,255].\n",
    "                                                      Useful for visually representing different classes (relevant for\n",
    "                                                      object detection).\n",
    "    half_line_width (non-negative integer): Plot using thicker lines.\n",
    "\n",
    "    Return:\n",
    "        SimpleITK image with rectangles plotted on it.\n",
    "    \"\"\"\n",
    "    # functions that convert from various bounding box representations to the [min_x, min_y, max_x, max_y] representation.\n",
    "    convert_to_minxy_maxxy = {\n",
    "        \"MINXY_MAXXY\": lambda original: original,\n",
    "        \"MINXY_WH\": lambda original: [\n",
    "            [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]\n",
    "            for bbox in original\n",
    "        ],\n",
    "        \"CENT_WH\": lambda original: [\n",
    "            [\n",
    "                bbox[0] - bbox[2] / 2.0,\n",
    "                bbox[1] - bbox[3] / 2.0,\n",
    "                bbox[0] + bbox[2] / 2.0,\n",
    "                bbox[1] + bbox[3] / 2.0,\n",
    "            ]\n",
    "            for bbox in original\n",
    "        ],\n",
    "        \"CENT_HALFWH\": lambda original: [\n",
    "            [bbox[0] - bbox[2], bbox[1] - bbox[3], bbox[0] + bbox[2], bbox[1] + bbox[3]]\n",
    "            for bbox in original\n",
    "        ],\n",
    "    }\n",
    "\n",
    "    # Confirm image is in expected format\n",
    "    pixel_type = image.GetPixelID()\n",
    "    num_channels = image.GetNumberOfComponentsPerPixel()\n",
    "    if pixel_type not in [sitk.sitkUInt8, sitk.sitkVectorUInt8]:\n",
    "        raise ValueError(\n",
    "            f\"Image channels expected to have type of 8-bit unsigned integer, got ({image.GetPixelIDTypeAsString()})\"\n",
    "        )\n",
    "    if num_channels not in [1, 3]:\n",
    "        raise ValueError(\n",
    "            f\"Image expected to have one or three channels, got ({num_channels})\"\n",
    "        )\n",
    "    if num_channels == 3:\n",
    "        overlay_image = sitk.Image(image)\n",
    "    else:\n",
    "        overlay_image = sitk.Compose([image] * 3)\n",
    "    if half_line_width < 0:\n",
    "        raise ValueError(\n",
    "            f\"Half line width parameter expected to be non-negative, got ({half_line_width})\"\n",
    "        )\n",
    "    # Convert bounding box information into standard format, based on user specification of the original format\n",
    "    try:\n",
    "        standard_bounding_boxes = convert_to_minxy_maxxy[bounding_box_format](\n",
    "            bounding_boxes\n",
    "        )\n",
    "        if normalized:\n",
    "            scale_x, scale_y = image.GetSize()\n",
    "            standard_bounding_boxes = [\n",
    "                [\n",
    "                    bbox[0] * scale_x,\n",
    "                    bbox[1] * scale_y,\n",
    "                    bbox[2] * scale_x,\n",
    "                    bbox[3] * scale_y,\n",
    "                ]\n",
    "                for bbox in standard_bounding_boxes\n",
    "            ]\n",
    "        # round to integer coordinates\n",
    "        standard_bounding_boxes = [\n",
    "            [int(b + 0.5) for b in bbox] for bbox in standard_bounding_boxes\n",
    "        ]\n",
    "    except KeyError:\n",
    "        raise ValueError(\n",
    "            f\"Unknown bounding box format ({bounding_box_format}), valid values are [MINXY_WH, MINXY_MAXXY, CENT_WH, CENT_HALFWH]\"\n",
    "        )\n",
    "    if not colors:  # use a single color for all bounding boxes\n",
    "        colors = [[255, 0, 0]] * len(standard_bounding_boxes)\n",
    "    line_width = 1 + 2 * half_line_width\n",
    "    for bbox, color in zip(standard_bounding_boxes, colors):\n",
    "        width = bbox[2] - bbox[0]\n",
    "        height = bbox[3] - bbox[1]\n",
    "        vert = sitk.Compose(\n",
    "            [\n",
    "                sitk.Image([line_width, height + line_width], sitk.sitkUInt8)\n",
    "                + color[0],\n",
    "                sitk.Image([line_width, height + line_width], sitk.sitkUInt8)\n",
    "                + color[1],\n",
    "                sitk.Image([line_width, height + line_width], sitk.sitkUInt8)\n",
    "                + color[2],\n",
    "            ]\n",
    "        )\n",
    "        horiz = sitk.Compose(\n",
    "            [\n",
    "                sitk.Image([width, line_width], sitk.sitkUInt8) + color[0],\n",
    "                sitk.Image([width, line_width], sitk.sitkUInt8) + color[1],\n",
    "                sitk.Image([width, line_width], sitk.sitkUInt8) + color[2],\n",
    "            ]\n",
    "        )\n",
    "        try:\n",
    "            overlay_image[\n",
    "                bbox[0] - half_line_width : bbox[0] + half_line_width + 1,\n",
    "                bbox[1] - half_line_width : bbox[3] + half_line_width + 1,\n",
    "            ] = vert\n",
    "            overlay_image[\n",
    "                bbox[2] - half_line_width : bbox[2] + half_line_width + 1,\n",
    "                bbox[1] - half_line_width : bbox[3] + half_line_width + 1,\n",
    "            ] = vert\n",
    "            overlay_image[\n",
    "                bbox[0] : bbox[2],\n",
    "                bbox[1] - half_line_width : bbox[1] + half_line_width + 1,\n",
    "            ] = horiz\n",
    "            overlay_image[\n",
    "                bbox[0] : bbox[2],\n",
    "                bbox[3] - half_line_width : bbox[3] + half_line_width + 1,\n",
    "            ] = horiz\n",
    "        except Exception:  # Drawing outside the border of the image will cause problems\n",
    "            continue\n",
    "    return overlay_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Read an image from the leg panorama dataset\n",
    "data_directory = os.path.dirname(fdata(\"leg_panorama/readme.txt\"))\n",
    "image = sitk.ReadImage(os.path.join(data_directory, \"hip.mha\"))\n",
    "\n",
    "# The overlay function expects the intensity values to be in [0,255] so rescale the original\n",
    "image = sitk.Cast(sitk.RescaleIntensity(image), sitk.sitkUInt8)\n",
    "# Set of bounding boxes, for the hip and two femur heads using the MINXY_MAXXY bounding box specification\n",
    "bounding_boxes = [[20, 11, 819, 434], [51, 204, 278, 452], [609, 194, 836, 455]]\n",
    "# Colors for the bounding boxes, based on associated classes\n",
    "colors = [[255, 0, 0], [0, 255, 0], [0, 255, 0]]\n",
    "res = overlay_bounding_boxes(\n",
    "    image=image,\n",
    "    bounding_boxes=bounding_boxes,\n",
    "    bounding_box_format=\"MINXY_MAXXY\",\n",
    "    colors=colors,\n",
    "    half_line_width=1,\n",
    ")\n",
    "gui.multi_image_display2D([res], figure_size=(6, 3));"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
